﻿using Grow.EventBus.Cap.PublisherDomainEvents;
using Grow.Module.Service;
using Grow.Scheduler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Grow.EventBus.Cap.SubscriberDomainEvents
{
    public class DomainEventSubscriber : IDomainEventSubscriber
    {
        private readonly IServiceContext _serviceContext;
        private readonly ISubscriberDomainEventHandler _subscriberDomainEventHandler;
        public DomainEventSubscriber(IServiceContext serviceContext)
        {
            _serviceContext = serviceContext;
            _subscriberDomainEventHandler = _serviceContext.GetRequiredService<ISubscriberDomainEventHandler>();
        }
        public async Task<bool> SubscriberAsync(SubscriberDomainEventDto subscriberDomainEventDto, CancellationToken cancellationToken = default)
        {
            try
            {
                await SaveSubscriberEventAsync(subscriberDomainEventDto, cancellationToken);
                // 非延迟事件直接进入执行队列
                await _subscriberDomainEventHandler.SubscriberAsync(subscriberDomainEventDto, cancellationToken);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private async Task SaveSubscriberEventAsync(SubscriberDomainEventDto subscriberDomainEventDto, CancellationToken cancellationToken)
        {
            var serviceContext = _serviceContext.GetServiceContext();
            var subscriberDomainEventService = serviceContext.GetRequiredService<ISubscriberDomainEventService>();
             await subscriberDomainEventService.SaveSubscriberEventAsync(subscriberDomainEventDto, cancellationToken);
        }
    }
}
